<?php
namespace Home\Controller;
use Think\Controller;

class OrderController extends CommonController {
	public function _initialize() {
		parent::_initialize();
		$this->cartSrv           = D('CartTmp');
		$this->commodityLimitSrv = D('CommodityLimit');
		$this->commoditySrv      = D('CommodityInfo');
		$this->commoditySrv->ini();
	}
	//获取行政区信息
	public function ajaxGetDistrict() {
		$city_id = num_f(I('city_id'));
		if (empty($city_id)) {
			$response['msg'] = '参数异常';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$addressDistrict = D('AddressDistrict');
		$db_res          = $addressDistrict->where("city_id = '" . $city_id . "'")->field("region_id,region_name")->select();
		if (empty($db_res)) {
			$response['msg'] = '获取失败';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$response['data'] = $db_res;
		$response['msg']  = '获取失败';
		$response['rsc']  = C('RESPONSE.SUCCESS');
		$this->ajaxReturn($response);
	}

	//新增用户配送地址（新增并设置默认值）
	public function ajaxAddUserAddress() {
		if ($this->checkLogin() == false) {
			$response['msg'] = '尚未登陆';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$user_id              = $this->uId();
		$data['uda_id']       = new_doc_id('UDA');
		$data['user_id']      = $user_id;
		$data['uda_name']     = I('uda_name'); //用户配置的易记的名字（家 公司） 非必填
		$data['consignee']    = I('consignee'); // 必填
		$data['city']         = I('city'); // 必填
		$data['district']     = I('district'); // 必填
		$data['address']      = I('address'); // 必填
		$data['zipcode']      = I('zipcode');
		$data['mobile']       = I('mobile'); // 必填
		$data['firstaddress'] = 1;
		if (empty($data['consignee']) || empty($data['city']) || empty($data['district']) || empty($data['address']) || empty($data['mobile'])) {
			$response['msg'] = '参数异常';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$userDeliveryAddress = D('UserDeliveryAddress');
		$userDeliveryAddress->data($data)->add();
		$userDeliveryAddress->where("user_id = '" . $user_id . "' and uda_id <> '" . $data['uda_id'] . "'")->save(array("firstaddress" => 0));
		$response['msg'] = '新增成功';
		$response['rsc'] = C('RESPONSE.SUCCESS');
		$this->ajaxReturn($response);
	}

	//获取用户配送地址列表
	public function ajaxGetUserAddress() {
		if ($this->checkLogin() == false) {
			$response['msg'] = '尚未登陆';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$user_id             = $this->uId();
		$userDeliveryAddress = D('UserDeliveryAddress');
		$db_res              = $userDeliveryAddress->where("user_id = '" . $user_id . "'")->select();
		if (empty($db_res)) {
			$response['msg'] = '暂无地址';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$response['data'] = $db_res;
		$response['msg']  = '获取成功';
		$response['rsc']  = C('RESPONSE.SUCCESS');
		$this->ajaxReturn($response);
	}

	//获取结算详情接口
	public function ajaxGetCartOrder() {
		$data = array();
		if ($this->checkLogin() == false) {
			$response['msg'] = '尚未登陆';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$user_id = $this->uId();
		//获取购物车商品列表
		$res = $this->cartSrv->getCartList($user_id);
		if ($res['isok'] == false) {
			$response['msg'] = $res['msg'];
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$cart_list = $res['data'];
		//检查库存 选择配送期
		$new_commoditys = array();
		foreach ($cart_list['list'] as $commodity) {
			$res = $this->commodityLimitSrv->checkLimit($commodity['commodity_id'], $commodity['commodity_num'], 1);
			if ($res == false) {
				$commodity['limit_error'] = '库存不足';
			}
			// $commodity['sale_cycle'] = $this->commoditySrv->hitLastSaleCycle($commodity['commodity_id']);
			$sale_cycle       = $this->commoditySrv->hitLastSaleCycle($commodity['commodity_id']);
			$sale_cycles      = $this->commoditySrv->hitSaleCycleInWeek($commodity['commodity_id']);
			$new_commoditys[] = $commodity;
		}
		$cart_list['list']    = $new_commoditys;
		$data['cart_list']    = $cart_list;
		$data['sale_cycle']   = $sale_cycle;
		$data['sale_cycles']   = $sale_cycles;
		$orderInfo            = D('OrderInfo');
		$data['shipping_fee'] = $orderInfo->getShippingFee($cart_list['sum']['sale_sum']);
		//获取默认配送地址
		$userDeliveryAddress = D('UserDeliveryAddress');

		$sql = 'SELECT
					uda.uda_id,
					uda.user_id,
					uda.consignee,
					ac.city_id,
					ac.city_name,
					ad.region_id,
					ad.region_name,
					uda.address,
					uda.mobile,
					uda.firstaddress
				FROM
					user_delivery_address AS uda
				LEFT JOIN address_city AS ac ON uda.city = ac.city_id
				LEFT JOIN address_district AS ad ON uda.district = ad.region_id
				WHERE
					uda.user_id = "' . $user_id . '"
				AND uda.firstaddress = 1';
		$db_res = $userDeliveryAddress->query($sql);

		if (!empty($db_res)) {
			$data['firstaddress'] = $db_res[0];
		} else {
			$data['firstaddress'] = null;
		}
		// $data['cue'] = "这里是提交订单的提示";
		$response['data'] = $data;
		$response['msg']  = $res['msg'];
		$response['rsc']  = C('RESPONSE.SUCCESS');
		$this->ajaxReturn($response);
	}

	//提交订单接口
	public function ajaxAddOrder() {
		if ($this->checkLogin() == false) {
			$response['msg'] = '尚未登陆';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$user_id           = $this->uId();
		$uda_id            = I('uda_id', null);
		$dispatch_datetime = I('dispatch_datetime', null);
		if (empty($dispatch_datetime) || empty($uda_id)) {
			$response['msg'] = '参数异常';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$dispatch_datetime = $dispatch_datetime;
		$order = D('OrderInfo');
		$res   = $order->addCommonOrder($user_id, $dispatch_datetime, $uda_id);
		if ($res['isok'] == false) {
			$response['msg'] = $res['msg'];
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		
		// 默认微信支付
		$paymentOnlineFlow = D('PaymentOnlineFlow');
		$data['flow_id'] = new_doc_id('ONLINE_FLOW');
		$data['type'] = 0;
		$data['status'] = 0;
		$data['relation_id'] = $res['payment_id'];
		$data['should_pay'] = $res['should_payment'];
		$paymentOnlineFlow->data($data)->add();
		
		
		$response['order_id'] = $res['order_id'];
		$response['href'] = C('HTTP_DOMAIN')."/Home/Wxmpay/index?flow_id=".$data['flow_id'];
		$response['msg']      = '下单成功';
		$response['rsc']      = C('RESPONSE.SUCCESS');
		$this->ajaxReturn($response);
	}

	//删除地址
	public function ajaxDeleteOneAddress() {
		$uda_id              = I('uda_id', '');
		$userDeliveryAddress = D('UserDeliveryAddress');
		$where['uda_id']     = $uda_id;
		$db_res              = $userDeliveryAddress->where($where)->delete();
		if ($db_res === false) {
			$response['msg'] = '删除失败';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$response['msg'] = '删除成功';
		$response['rsc'] = C('RESPONSE.SUCCESS');
		$this->ajaxReturn($response);
	}

	//设为默认
	public function ajaxSetAddressDefault() {
		$uda_id               = I('uda_id', '');
		$userDeliveryAddress  = D('UserDeliveryAddress');
		$user_id              = $this->uId();
		$where                = array();
		$data                 = array();
		$where['user_id']     = $user_id;
		$data['firstaddress'] = 0;
		$db_res               = $userDeliveryAddress->where($where)->save($data);
		if ($db_res === false) {
			$response['msg'] = '设置成功';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$where['uda_id']      = $uda_id;
		$data['firstaddress'] = 1;
		$db_res               = $userDeliveryAddress->where($where)->save($data);
		if ($db_res === false) {
			$response['msg'] = '设置失败';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$response['msg'] = '设置成功';
		$response['rsc'] = C('RESPONSE.SUCCESS');
		$this->ajaxReturn($response);
	}

	//获取详情
	public function ajaxGetAddressInfoById() {
		$uda_id              = I('uda_id', '');
		$userDeliveryAddress = D('UserDeliveryAddress');
		$where['uda_id']     = $uda_id;
		$db_res              = $userDeliveryAddress->where($where)->select();
		$response['data']    = $db_res[0];
		$response['msg']     = '获取成功';
		$response['rsc']     = C('RESPONSE.SUCCESS');
		$this->ajaxReturn($response);
	}

	//更新地址
	public function ajaxModifyAddress() {
		$where['uda_id']     = I('uda_id');
		$data['uda_name']    = I('uda_name'); //用户配置的易记的名字（家 公司） 非必填
		$data['consignee']   = I('consignee'); // 必填
		$data['city']        = I('city'); // 必填
		$data['district']    = I('district'); // 必填
		$data['address']     = I('address'); // 必填
		$data['zipcode']     = I('zipcode');
		$data['mobile']      = I('mobile'); // 必填
		$userDeliveryAddress = D('UserDeliveryAddress');
		$db_res              = $userDeliveryAddress->where($where)->save($data);
		if ($db_res === false) {
			$response['msg'] = '修改失败';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$response['msg'] = '修改成功';
		$response['rsc'] = C('RESPONSE.SUCCESS');
		$this->ajaxReturn($response);
	}

	// 获取订单列表
	public function ajaxGetOrderList() {
		$pageno   = I('pageno');
		$pagesize = I('pagesize');
		$order_page = I('order_page');// 1 进行 0 废除
		$payment_status = I('payment_status',null); //1待支付、10已支付
		if (empty($pageno)) {
			$pageno = 1;
		}

		if (empty($pagesize)) {
			$pagesize = 10;
		}
		if ($this->checkLogin() == false) {
			$response['toLogin'] = 1;
			$response['msg'] = '尚未登陆';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$user_id          = $this->uId();
		$orderInfo        = D('OrderInfo');
		$res             = $orderInfo->getOrderList($user_id,$order_page,$payment_status,$pageno, $pagesize);
		$response['data'] = $res;
		$response['msg']  = '获取成功';
		$response['rsc']  = C('RESPONSE.SUCCESS');
		$this->ajaxReturn($response);
	}

	// 获取订单详情
	public function ajaxGetOrderInfo() {
		$order_id = I('order_id');
		if (empty($order_id)) {
			$response['msg'] = '参数异常';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$user_id          = $this->uId();
		$orderInfo        = D('OrderInfo');
		$data             = $orderInfo->getOrderInfo($order_id, $user_id);
		$response['data'] = $data;
		$response['msg']  = '获取成功';
		$response['rsc']  = C('RESPONSE.SUCCESS');
		$this->ajaxReturn($response);
	}
	
	// 取消订单接口
	public function ajaxCancelOrder(){
		if ($this->checkLogin() == false) {
			$response['msg'] = '尚未登陆';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$user_id  = $this->uId();
		$order_id = I('order_id');
		if (empty($order_id)) {
			$response['msg'] = '参数异常';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$OrderInfo = D('OrderInfo');
		$res = $OrderInfo->cancelOrder($order_id,$user_id);
		if($res['isok']==false){
			$response['msg']  = $res['msg'];
			$response['rsc']  = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$response['msg']  = '操作成功';
		$response['rsc']  = C('RESPONSE.SUCCESS');
		$this->ajaxReturn($response);
	}
	
};